package we.core.handlers;

import java.nio.channels.SocketChannel;

import java.util.HashMap;
import java.util.Map;

import we.core.bean.CDataContainer;

import we.core.bean.CRoom;

import we.core.bean.CUser;

import we.extension.CSystemEvent;

import org.json.JSONException;
import org.json.JSONObject;

public class COutRoomHandler extends CAbstractCoreHandler {
    public COutRoomHandler() {
    }

    public int handleEvent(SocketChannel channel, JSONObject data) {       
        String username;
        int fromRoomId;
        try {
            username = data.getString("username");
            fromRoomId = data.getInt("fromRoomId");
            CRoom r = CDataContainer.instance().getRoom(fromRoomId);
            if(r!=null){                
                r.removeUser(username);
                CUser u = CDataContainer.instance().getUser(username);
                u.roomId = -1;            
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("eventName", CSystemEvent.SystemEventType.OUT_ROOM);
                params.put("user", u);
                params.put("fromRoomId", u.roomId);
                CSystemEvent se = new CSystemEvent(this, params);
                dispatchSystemEvent(se);
            }
        } catch (JSONException e) {
            // TODO
        }
        return 0;
    }
}
